<!--
 * @Date: 2025-01-08 11:42:28
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-01-08 11:49:26
 * @Description: 签名图片上传
-->
<template>
  <el-form-item label="签名图片" style="justify-content: flex-end;">
    <el-upload
      action="#"
      accept=".png, .jpg, .jpeg"
      list-type="picture-card"
      :limit='1'
      :disabled="disabled"
      :file-list="files"
      :auto-upload="false"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :before-upload="beforeUpload"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-form-item>
</template>
<script setup name="SignUploadPanel">
import { onMounted, reactive, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { defAxios as request } from '@/utils/http'

const props = defineProps({
  formData: {
    type: Object,
    default: () => { return { EXPERT_ID: '' } },
  },
  disabled: { type: Boolean },
  formType: { type: String },
  limitSize:{ type: Number, default: 1 }
});


const files = ref([])
const dialogVisible = ref(false);
const dialogImageUrl = ref('');

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 <= props.limitSize; // 小于2MB
  if (!isLt2M) {
    ElMessage.warning(`上传的文件大小不能超过 1MB!`);
  }
  return isLt2M;
}
const handleRemove = (file, fileList) => {
  files.value = fileList
}
const handleExceed = (currentFiles, fileList) => {
  ElMessage.warning(`当前限制选择 1 个文件`);
}
const handleChange = (file, fileList) => {
  files.value = fileList
}
const handlePreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

/**
 * 设置图片
 * @param base64Array
 */
const setPicture = (base64Array) => {
  let fileArray = []
  //base64转换为Blob Url
  for (let base64 of base64Array) {
    if (!base64) continue
    const byteArrays = [];
    const byteCharacters = atob(base64.split(",")[1])
    for (let i = 0; i < byteCharacters.length; i++) {
      byteArrays.push(byteCharacters.charCodeAt(i))
    }
    let type = getMimeTypeFromBase64(base64)
    const blob = new Blob([new Uint8Array(byteArrays)], { type })
    const blobUrl = URL.createObjectURL(blob);
    fileArray.push({ name: '', url: blobUrl, type })
  }
  files.value = fileArray
}

/**
 * 获取图片
 * @returns {Promise<unknown>}
 */
const getPicture = () => {
  return new Promise(async (resolve, reject) => {
    let fileBase64Array = []
    for (let file of files.value) {
      const { url } = file
      const blob = await fetch(url).then(resp => resp.blob())
      let fileReader = new FileReader();
      fileReader.readAsDataURL(blob);
      const result = await new Promise((resolve, reject) => {
        fileReader.onload = (e) => {
          resolve(e.target.result)
        }
      })
      fileBase64Array.push(result)
    }
    resolve(fileBase64Array)
  })
}

/**
 * 获取Base64文件类型
 */
const getMimeTypeFromBase64 = (base64String) => {
  const prefix = base64String.slice(0, 20);
  switch (true) {
    case /^data:image\/jpeg;base64,/.test(prefix):
      return 'image/jpeg';
    case /^data:image\/png;base64,/.test(prefix):
      return 'image/png';
    case /^data:image\/gif;base64,/.test(prefix):
      return 'image/gif';
    case /^data:application\/pdf;base64,/.test(prefix):
      return 'application/pdf';
    // Add more MIME types as needed
    default:
      return 'image/png';
  }
}

// ----- 获取组件数据
/**
 * 暴露给表单调用，固定名称getCompData
 */
const getCompData = async function () {
  const pic = await getPicture()
  return {
    signature: pic[0] || '',
  };
};
// ----- 校验组件数据
/**
 * 暴露给表单调用，固定名称validateData
 */
const validateData = async function () {
  return { valid: true, message: '校验通过！' };
};

//请求初始化数据
onMounted(async () => {
  if (props.formData.EXPERT_ID) {
    const res = await request({
      url: '/expert/getExpertOther',
      method: 'post',
      data: { expertId: props.formData.EXPERT_ID }
    })
    if (res.code === 200 && res.data) {
      setPicture([res.data.signatureStr])
    }
  }
});

defineExpose({
  getCompData,
  validateData,
})
</script>

<style scoped lang="scss">
</style>
